using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Phoenix;
using Phoenix.Commands;
using TodoApp.Models;

namespace TodoApp.Features.Tasks
{
    public class IndexViewModel : ViewModelBase
    {
        public IndexViewModel(IEnumerable<TodoTask> tasks)
        {
            Tasks = new ObservableCollection<TodoTask>(tasks.OrderBy(t=>t.Title));
            CreateTaskCommand = new DelegateCommand(CreateTask);
        }

        void CreateTask()
        {
            Controller<TasksController>()
                .InvokeActionWithResult<CreateTaskResult>(c => c.Create())
                .ContinueWith(t =>
                    {
                        if (t.Result.TaskCreated)
                        {
                            AddToList(t.Result.Task);
                        }
                    }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        public ObservableCollection<TodoTask> Tasks { get; private set; }

        public ICommand CreateTaskCommand { get; private set; }

        void AddToList(TodoTask task)
        {
            int i;
            for (i = 0; i < Tasks.Count; i++)
            {
                if (String.CompareOrdinal(Tasks[0].Title, task.Title) >= 0)
                    break;
            }
            var insertAt = i - 1;
            if (insertAt < 0)
                insertAt = 0;
            Tasks.Insert(insertAt, task);
        }
    }
}